"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { 
  MessageSquare, 
  Plus, 
  Search, 
  Send,
  ArrowLeft,
  User,
  Calendar,
  Star,
  MoreHorizontal,
  Edit,
  Trash2,
  Reply,
  ThumbsUp,
  AlertCircle
} from "lucide-react"
import { cn } from "@/lib/utils"

interface Feedback {
  _id: string
  title: string
  content: string
  type: 'bug' | 'suggestion' | 'question' | 'complaint' | 'praise'
  priority: 'low' | 'medium' | 'high' | 'urgent'
  status: 'open' | 'in_progress' | 'resolved' | 'closed'
  createdBy: string
  createdByName: string
  createdAt: string
  updatedAt: string
  projectId: string
  assignee?: string
  assigneeName?: string
  replies?: FeedbackReply[]
  rating?: number
  tags?: string[]
}

interface FeedbackReply {
  _id: string
  content: string
  createdBy: string
  createdByName: string
  createdAt: string
  feedbackId: string
}

export default function ProjectFeedbackPage() {
  const params = useParams()
  const router = useRouter()
  const projectId = params.id as string
  
  const [feedbacks, setFeedbacks] = useState<Feedback[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState("")
  const [typeFilter, setTypeFilter] = useState<string>("all")
  const [statusFilter, setStatusFilter] = useState<string>("all")
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [newFeedback, setNewFeedback] = useState({
    title: '',
    content: '',
    type: 'suggestion' as Feedback['type'],
    priority: 'medium' as Feedback['priority']
  })

  useEffect(() => {
    loadFeedbacks()
  }, [projectId])

  const loadFeedbacks = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/projects/${projectId}/feedback`)
      if (response.ok) {
        const feedbacksData = await response.json()
        setFeedbacks(feedbacksData)
      }
    } catch (error) {
      console.error('加载反馈失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'bug': return 'bg-red-500'
      case 'suggestion': return 'bg-blue-500'
      case 'question': return 'bg-yellow-500'
      case 'complaint': return 'bg-orange-500'
      case 'praise': return 'bg-green-500'
      default: return 'bg-gray-500'
    }
  }

  const getTypeText = (type: string) => {
    switch (type) {
      case 'bug': return '问题反馈'
      case 'suggestion': return '建议'
      case 'question': return '咨询'
      case 'complaint': return '投诉'
      case 'praise': return '表扬'
      default: return type
    }
  }

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'bug': return AlertCircle
      case 'suggestion': return MessageSquare
      case 'question': return MessageSquare
      case 'complaint': return AlertCircle
      case 'praise': return Star
      default: return MessageSquare
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'open': return 'bg-gray-500'
      case 'in_progress': return 'bg-blue-500'
      case 'resolved': return 'bg-green-500'
      case 'closed': return 'bg-purple-500'
      default: return 'bg-gray-500'
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'open': return '待处理'
      case 'in_progress': return '处理中'
      case 'resolved': return '已解决'
      case 'closed': return '已关闭'
      default: return status
    }
  }

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'low': return 'bg-green-500'
      case 'medium': return 'bg-yellow-500'
      case 'high': return 'bg-orange-500'
      case 'urgent': return 'bg-red-500'
      default: return 'bg-gray-500'
    }
  }

  const getPriorityText = (priority: string) => {
    switch (priority) {
      case 'low': return '低'
      case 'medium': return '中'
      case 'high': return '高'
      case 'urgent': return '紧急'
      default: return priority
    }
  }

  const filteredFeedbacks = feedbacks.filter(feedback => {
    const matchesSearch = feedback.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         feedback.content.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesType = typeFilter === "all" || feedback.type === typeFilter
    const matchesStatus = statusFilter === "all" || feedback.status === statusFilter
    
    return matchesSearch && matchesType && matchesStatus
  })

  const handleSubmitFeedback = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!newFeedback.title.trim() || !newFeedback.content.trim()) {
      return
    }

    try {
      const response = await fetch(`/api/projects/${projectId}/feedback`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newFeedback)
      })

      if (response.ok) {
        setNewFeedback({
          title: '',
          content: '',
          type: 'suggestion',
          priority: 'medium'
        })
        setShowCreateForm(false)
        loadFeedbacks()
      }
    } catch (error) {
      console.error('提交反馈失败:', error)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载反馈中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 页面头部 */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button variant="ghost" size="sm" onClick={() => router.back()}>
                <ArrowLeft className="h-4 w-4" />
              </Button>
              <div>
                <h1 className="text-2xl font-bold text-gray-900">项目反馈</h1>
                <p className="text-sm text-gray-500">收集和管理项目相关的反馈意见</p>
              </div>
            </div>
            <Button onClick={() => setShowCreateForm(true)}>
              <Plus className="h-4 w-4 mr-2" />
              新建反馈
            </Button>
          </div>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 创建反馈表单 */}
        {showCreateForm && (
          <Card className="mb-6">
            <CardHeader>
              <CardTitle>新建反馈</CardTitle>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSubmitFeedback} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    标题 *
                  </label>
                  <Input
                    value={newFeedback.title}
                    onChange={(e) => setNewFeedback({...newFeedback, title: e.target.value})}
                    placeholder="请输入反馈标题"
                    required
                  />
                </div>
                
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      反馈类型
                    </label>
                    <Select 
                      value={newFeedback.type} 
                      onValueChange={(value: Feedback['type']) => setNewFeedback({...newFeedback, type: value})}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="bug">问题反馈</SelectItem>
                        <SelectItem value="suggestion">建议</SelectItem>
                        <SelectItem value="question">咨询</SelectItem>
                        <SelectItem value="complaint">投诉</SelectItem>
                        <SelectItem value="praise">表扬</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      优先级
                    </label>
                    <Select 
                      value={newFeedback.priority} 
                      onValueChange={(value: Feedback['priority']) => setNewFeedback({...newFeedback, priority: value})}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="low">低</SelectItem>
                        <SelectItem value="medium">中</SelectItem>
                        <SelectItem value="high">高</SelectItem>
                        <SelectItem value="urgent">紧急</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    详细描述 *
                  </label>
                  <Textarea
                    value={newFeedback.content}
                    onChange={(e) => setNewFeedback({...newFeedback, content: e.target.value})}
                    placeholder="请详细描述您的反馈内容..."
                    rows={4}
                    required
                  />
                </div>
                
                <div className="flex justify-end space-x-2">
                  <Button type="button" variant="outline" onClick={() => setShowCreateForm(false)}>
                    取消
                  </Button>
                  <Button type="submit">
                    <Send className="h-4 w-4 mr-2" />
                    提交反馈
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        )}

        {/* 搜索和筛选 */}
        <Card className="mb-6">
          <CardContent className="pt-6">
            <div className="flex flex-col sm:flex-row gap-4">
              <div className="flex-1">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                  <Input
                    placeholder="搜索反馈..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>
              <div className="flex gap-2">
                <Select value={typeFilter} onValueChange={setTypeFilter}>
                  <SelectTrigger className="w-32">
                    <SelectValue placeholder="类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部类型</SelectItem>
                    <SelectItem value="bug">问题反馈</SelectItem>
                    <SelectItem value="suggestion">建议</SelectItem>
                    <SelectItem value="question">咨询</SelectItem>
                    <SelectItem value="complaint">投诉</SelectItem>
                    <SelectItem value="praise">表扬</SelectItem>
                  </SelectContent>
                </Select>
                
                <Select value={statusFilter} onValueChange={setStatusFilter}>
                  <SelectTrigger className="w-32">
                    <SelectValue placeholder="状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部状态</SelectItem>
                    <SelectItem value="open">待处理</SelectItem>
                    <SelectItem value="in_progress">处理中</SelectItem>
                    <SelectItem value="resolved">已解决</SelectItem>
                    <SelectItem value="closed">已关闭</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 反馈列表 */}
        <div className="space-y-4">
          {filteredFeedbacks.length === 0 ? (
            <Card>
              <CardContent className="pt-12 pb-12">
                <div className="text-center">
                  <MessageSquare className="h-12 w-12 mx-auto mb-4 text-gray-400" />
                  <h3 className="text-lg font-medium text-gray-900 mb-2">暂无反馈</h3>
                  <p className="text-gray-500 mb-4">
                    {searchTerm || typeFilter !== "all" || statusFilter !== "all" 
                      ? "没有找到符合条件的反馈" 
                      : "开始收集第一个反馈来改进项目"
                    }
                  </p>
                  <Button onClick={() => setShowCreateForm(true)}>
                    <Plus className="h-4 w-4 mr-2" />
                    新建反馈
                  </Button>
                </div>
              </CardContent>
            </Card>
          ) : (
            filteredFeedbacks.map((feedback) => {
              const TypeIcon = getTypeIcon(feedback.type)
              return (
                <Card key={feedback._id} className="hover:shadow-md transition-shadow">
                  <CardContent className="pt-6">
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center space-x-3 mb-2">
                          <TypeIcon className="h-5 w-5 text-gray-400" />
                          <h3 className="text-lg font-medium text-gray-900">{feedback.title}</h3>
                          <Badge className={getTypeColor(feedback.type)}>
                            {getTypeText(feedback.type)}
                          </Badge>
                          <Badge className={getStatusColor(feedback.status)}>
                            {getStatusText(feedback.status)}
                          </Badge>
                          <Badge className={getPriorityColor(feedback.priority)}>
                            {getPriorityText(feedback.priority)}
                          </Badge>
                        </div>
                        
                        <p className="text-gray-600 mb-4">{feedback.content}</p>
                        
                        <div className="flex flex-wrap items-center gap-4 text-sm text-gray-500">
                          <div className="flex items-center">
                            <User className="h-4 w-4 mr-1" />
                            {feedback.createdByName || '匿名用户'}
                          </div>
                          <div className="flex items-center">
                            <Calendar className="h-4 w-4 mr-1" />
                            {new Date(feedback.createdAt).toLocaleDateString()}
                          </div>
                          {feedback.assigneeName && (
                            <div className="flex items-center">
                              <span>处理人: {feedback.assigneeName}</span>
                            </div>
                          )}
                          {feedback.rating && (
                            <div className="flex items-center">
                              <Star className="h-4 w-4 mr-1 text-yellow-400" />
                              {feedback.rating}/5
                            </div>
                          )}
                          {feedback.replies && feedback.replies.length > 0 && (
                            <div className="flex items-center">
                              <MessageSquare className="h-4 w-4 mr-1" />
                              {feedback.replies.length} 条回复
                            </div>
                          )}
                        </div>
                        
                        {feedback.tags && feedback.tags.length > 0 && (
                          <div className="flex flex-wrap gap-2 mt-3">
                            {feedback.tags.map((tag, index) => (
                              <Badge key={index} variant="outline" className="text-xs">
                                {tag}
                              </Badge>
                            ))}
                          </div>
                        )}
                      </div>
                      
                      <div className="flex items-center space-x-2 ml-4">
                        <Button variant="ghost" size="sm">
                          <Reply className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="sm">
                          <ThumbsUp className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="sm">
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="sm">
                          <Trash2 className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="sm">
                          <MoreHorizontal className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )
            })
          )}
        </div>

        {/* 统计信息 */}
        <Card className="mt-6">
          <CardHeader>
            <CardTitle className="text-lg">反馈统计</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-gray-600">
                  {feedbacks.filter(f => f.status === 'open').length}
                </div>
                <div className="text-sm text-gray-500">待处理</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-600">
                  {feedbacks.filter(f => f.status === 'in_progress').length}
                </div>
                <div className="text-sm text-gray-500">处理中</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-green-600">
                  {feedbacks.filter(f => f.status === 'resolved').length}
                </div>
                <div className="text-sm text-gray-500">已解决</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-gray-600">
                  {feedbacks.length}
                </div>
                <div className="text-sm text-gray-500">总反馈</div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}